package com.zhao.controller;

import com.zhao.common.util.RandomUtil;
import com.zhao.common.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RestController
@RequestMapping
public class SignController {

    @Value("${test.privateKeyStr}")
    private String privateKeyStr;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/sign")
    public String sign() throws Exception {
        String mchId = "1900009191";
        String method = "GET";
        String canonicalUrl = "/v1/account/getAccount?name=abc";
        String body = "";
        String nonceStr = RandomUtil.getRandomString(6);
        String serialNo = "";
        long timestamp = System.currentTimeMillis();
        String token = "WECHATPAY2-SHA256-RSA2048 " + SignUtil.getToken(method, canonicalUrl, timestamp, body, mchId, privateKeyStr, nonceStr, serialNo);
        log.info(token);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8083" + canonicalUrl, HttpMethod.GET, requestEntity, String.class);
        return response.getBody();
    }

    @RequestMapping("/sign1")
    public String sign1() throws Exception {
        String mchId = "1900009191";
        String method = "POST";
        String canonicalUrl = "/v1/account/postAccount";
        String body = "message";
        String nonceStr = RandomUtil.getRandomString(6);
        String serialNo = "";
        long timestamp = System.currentTimeMillis();
        String token = "WECHATPAY2-SHA256-RSA2048 " + SignUtil.getToken(method, canonicalUrl, timestamp, body, mchId, privateKeyStr, nonceStr, serialNo);
        log.info(token);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8083" + canonicalUrl, HttpMethod.POST, requestEntity, String.class);
        return response.getBody();
    }
}
